package com.smile.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.smile.api.RoleApi;
import com.smile.commons.constant.StateConstant;
import com.smile.api.UserApi;
import com.smile.commons.md5.MD5Util;
import com.smile.commons.page.R;
import com.smile.model.dto.request.DoLoginRequestDTO;
import com.smile.model.request.GetRoleByIdRequest;
import com.smile.model.request.GetUserInfoByUserNameRequest;
import com.smile.model.response.GetRoleByIdResponse;
import com.smile.model.response.GetUserInfoByUserNameResponse;
import com.smile.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserApi userApi;
    
    @Autowired
    private RoleApi roleApi;



    @Override
    public Boolean doLogin(DoLoginRequestDTO doLoginRequestDTO) {
        GetUserInfoByUserNameRequest getUserInfoByUserNameRequest = new GetUserInfoByUserNameRequest();
        getUserInfoByUserNameRequest.setUserName(doLoginRequestDTO.getUsername());
        R<GetUserInfoByUserNameResponse> userInfoByUserName = userApi.getUserInfoByUserName(getUserInfoByUserNameRequest);
        if (ObjectUtil.isNotNull(userInfoByUserName) || ObjectUtil.isNotNull(userInfoByUserName.getData())) {

            if (userInfoByUserName.getData().getStatus()!=3){
                throw new RuntimeException("该用户无权限登录");
            }

            if (userInfoByUserName.getData().getPassword().
                    equals(MD5Util.md5WithSalt(doLoginRequestDTO.getPassword(), userInfoByUserName.getData().getSalt()))) {

                // 校验角色状态，禁用则拒绝登录
                Long roleId = userInfoByUserName.getData().getRoleId();
                if (ObjectUtil.isNotNull(roleId)) {
                    GetRoleByIdRequest request = new GetRoleByIdRequest();
                    request.setId(roleId);
                    R<GetRoleByIdResponse> roleResult = roleApi.getRoleById(request);
                    if (ObjectUtil.isNotNull(roleResult) && ObjectUtil.isNotNull(roleResult.getData())) {
                        if (StateConstant.DISABLE_STATE.equals(roleResult.getData().getStatus())) {
                            throw new RuntimeException("用户无权限，请联系管理员");
                        }
                    }
                }

                StpUtil.login(userInfoByUserName.getData().getId());
                return Boolean.TRUE;
            } else {
                return Boolean.FALSE;
            }
        } else {

            return Boolean.FALSE;
        }
    }
}
